import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import { LogService } from '../views/log/log.service';

@Injectable()
export class LoggingMiddleware implements NestMiddleware {
  constructor(private readonly logService: LogService) {}

  use(req: Request, res: Response, next: NextFunction) {
    const startTime = Date.now();

    // 记录请求开始
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.originalUrl} - 请求开始`);

    // 监听响应结束事件
    res.on('finish', () => {
      const responseTime = Date.now() - startTime;
      const statusCode = res.statusCode;
      
      // 记录请求完成
      console.log(`[${new Date().toISOString()}] ${req.method} ${req.originalUrl} - ${statusCode} (${responseTime}ms)`);
      
      // 如果是错误状态码，记录错误日志
      if (statusCode >= 400) {
        this.logService.logError(
          new Error(`HTTP ${statusCode}`),
          'middleware',
          req
        );
      }
    });

    next();
  }
}
